//
//  LastComViewController.m
//  BSLCar
//
//  Created by 梁毅 on 15/5/30.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "LastComViewController.h"
#import "LastComCollectionViewCell.h"
#import <UIImageView+WebCache.h>
#import <SDImageCache.h>
#import "MJRefresh.h"
#import "LCModel.h"
//#import "PictureViewController.h"
#import "CollectionPictureViewController.h"

@interface LastComViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UICollectionView *mCollection;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) UIActivityIndicatorView *activityindic;
@property (nonatomic) NSInteger pageIndex;
@property (nonatomic, retain) UICollectionViewFlowLayout *layout;
@property (nonatomic) NSInteger isExist;
@property (nonatomic, retain) NSString *typeID;
@property (nonatomic, retain) UIAlertView *alert;
@property (nonatomic) NSInteger pagecount;

@property (nonatomic) NSInteger piccount;

@property (nonatomic, retain) UIImageView *imageview;

@end

@implementation LastComViewController

- (void)dealloc
{
    [_serid release];
    [_name release];
    [_sp release];
    
    [_mCollection release];
    [_dataArray release];
    [_activityindic release];
    [_layout release];
    [_typeID release];
    [_alert release];
    [_imageview release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];
    
    self.navigationItem.title = self.name;
    
    self.imageview = [[UIImageView alloc] init];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.itemSize = CGSizeMake(self.view.bounds.size.width / 3 - 10, self.view.bounds.size.width / 3 - 40);
//    self.layout.sectionInset = UIEdgeInsetsMake(0, 0, 5, 0);
    self.mCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 37, self.view.bounds.size.width, self.view.bounds.size.height - 37 - 64) collectionViewLayout:self.layout];
    
    self.pageIndex = 1;
    self.typeID = @"1";

    self.alert = [[UIAlertView alloc] initWithTitle:@"没有更多数据了" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
    
    self.activityindic = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityindic.color = [UIColor grayColor];
    self.activityindic.center = self.view.center;
    [self.view addSubview:self.activityindic];
    [self.activityindic startAnimating];
    
    self.dataArray = [NSMutableArray array];
    
    [self selectTypeView];
    [self parserUrlRequest];
    
    [_activityindic release];
    [_layout release];
}

- (void)selectTypeView {
    UILabel *lableH1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 2, self.view.bounds.size.width, 1)];
    lableH1.backgroundColor = [UIColor grayColor];
    
    UILabel *lableH2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, self.view.bounds.size.width, 1)];
    lableH2.backgroundColor = [UIColor grayColor];
    
    self.imageview.frame = CGRectMake(10, 32, self.view.bounds.size.width / 4 - 20, 2);
    self.imageview.backgroundColor = [UIColor blueColor];
    [self.view addSubview:self.imageview];
    
    UILabel *lableV1 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 4, 2, 1, 33)];
    lableV1.backgroundColor = [UIColor grayColor];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(lableV1.frame.origin.x / 2 - 40, 3, 80, 30);
    [button1 setTitle:@"外观" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button1 addTarget:self action:@selector(typeSelect:) forControlEvents:UIControlEventTouchUpInside];
    button1.tag = 1;
    
    UILabel *lableV2 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 4 * 2, 2, 1, 33)];
    lableV2.backgroundColor = [UIColor grayColor];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake((lableV2.frame.origin.x + lableV1.frame.origin.x) / 2 - 20, 10, 40, 20);
    [button2 setTitle:@"座椅" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button2 addTarget:self action:@selector(typeSelect:) forControlEvents:UIControlEventTouchUpInside];
    button2.tag = 3;
    
    UILabel *lableV3 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 4 * 3, 2, 1, 33)];
    lableV3.backgroundColor = [UIColor grayColor];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake((lableV2.frame.origin.x + lableV3.frame.origin.x) / 2 - 40, 3, 80, 30);
    [button3 setTitle:@"中控" forState:UIControlStateNormal];
    [button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button3 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button3 addTarget:self action:@selector(typeSelect:) forControlEvents:UIControlEventTouchUpInside];
    button3.tag = 10;
    
    UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
    button4.frame = CGRectMake((self.view.bounds.size.width + lableV3.frame.origin.x) / 2 - 40, 3, 80, 30);
    [button4 setTitle:@"其他" forState:UIControlStateNormal];
    [button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button4 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button4 addTarget:self action:@selector(typeSelect:) forControlEvents:UIControlEventTouchUpInside];
    button4.tag = 12;
    
    [self.view addSubview:lableH1];
    [self.view addSubview:lableH2];
    
    [self.view addSubview:lableV1];
    [self.view addSubview:lableV2];
    [self.view addSubview:lableV3];
    
    [self.view addSubview:button1];
    [self.view addSubview:button2];
    [self.view addSubview:button3];
    [self.view addSubview:button4];
    
    [lableH1 release];
    [lableH2 release];
    
    [lableV1 release];
    [lableV2 release];
    [lableV3 release];
}

- (void)typeSelect:(UIButton *)sender {
    self.dataArray = [NSMutableArray array];
    if (sender.tag == 1) {
        [UIView animateWithDuration:.5 animations:^{
            self.imageview.frame = CGRectMake(10, 32, self.view.bounds.size.width / 4 - 20, 2);
        }];
    }
    if (sender.tag == 3) {
        [UIView animateWithDuration:.5 animations:^{
            self.imageview.frame = CGRectMake(10 + self.view.bounds.size.width / 4, 32, self.view.bounds.size.width / 4 - 20, 2);
        }];
    }
    if (sender.tag == 10) {
        [UIView animateWithDuration:.5 animations:^{
            self.imageview.frame = CGRectMake(10 + self.view.bounds.size.width / 4 * 2, 32, self.view.bounds.size.width / 4 - 20, 2);
        }];
    }
    if (sender.tag == 12) {
        [UIView animateWithDuration:.5 animations:^{
            self.imageview.frame = CGRectMake(10 + self.view.bounds.size.width / 4 * 3, 32, self.view.bounds.size.width / 4 - 20, 2);
        }];
    }
    self.typeID = [NSString stringWithFormat:@"%ld", sender.tag];
    self.pageIndex = 1;
    [self parserUrlRequest];
    [self.mCollection reloadData];
}

- (void)parserUrlRequest { //  cg 1 外观 10中控  3座椅  12其他
    NSString *string = @"http://baojiac.qichecdn.com/v3.5.5/cars/pics-a2-pm2-v3.9.2-ss";
    string = [NSString stringWithFormat:@"%@%@-sp%@-cg%@-cl0-p%ld-s60.html", string, self.serid, self.sp, self.typeID, self.pageIndex];
    NSURL *url = [NSURL URLWithString:string];
//    NSLog(@"%@", string);
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //        NSLog(@"%ld---", self.pageIndex);
            NSDictionary *dict = [diction objectForKey:@"result"];
            NSArray *array = [dict objectForKey:@"piclist"];
            self.piccount = [[dict objectForKey:@"rowcount"] integerValue];
            self.pagecount = [[dict objectForKey:@"pagecount"] integerValue];
            self.isExist = array.count;
            for (NSDictionary *dic in array) {
                LCModel *model = [LCModel getLCModel];
                model.picurl = [dic objectForKey:@"smallpic"];
                model.specname = [dic objectForKey:@"specname"];
                [self.dataArray addObject:model];
            }
            [self.activityindic stopAnimating];
            [self creatView];
            [self.mCollection reloadData];
        }
    }];
}

- (void)creatView {
    self.mCollection.backgroundColor = [UIColor colorWithRed:220 / 255.0 green:220 / 255.0 blue:220 / 255.0 alpha:1];
    self.mCollection.delegate = self;
    self.mCollection.dataSource = self;
    [self.mCollection registerClass:[LastComCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    [self.view addSubview:self.mCollection];
    
    [self.mCollection addHeaderWithTarget:self action:@selector(xiala)];
    [self.mCollection addFooterWithTarget:self action:@selector(shangla)];
}

- (void)xiala {
    if (self.pageIndex > 1) {
        [self.mCollection reloadData];
    }
    [self.mCollection headerEndRefreshing];
}

- (void)shangla {
    if (self.pageIndex < self.pagecount) {
        self.pageIndex++;
        [self parserUrlRequest];
        [self.mCollection reloadData];
    } else {
        [self.alert show];
    }
    [self.mCollection footerEndRefreshing];
//    NSLog(@"%ld", self.pageIndex);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LastComCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];

    LCModel *model = [self.dataArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:model.picurl];
    [cell.picture sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];

    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    CollectionPictureViewController *picture = [[CollectionPictureViewController alloc] init];
    picture.piccount = self.piccount;
    picture.index = indexPath.row;
    picture.pageindex = self.pageIndex;
    picture.dataArray = self.dataArray;
    picture.serid = self.serid;
    picture.typeId = self.typeID;
    picture.pagecount = self.pagecount;
    [self.navigationController pushViewController:picture animated:YES];
    [picture release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
